<template>
  <div class="main_box">
    <div class="add_wrap">
      <el-form :model="appointForm" ref="appointForm" label-width="200px" :rules="roleRules">
        <div class="tit" v-if="userRole === 1">
          <h2>医院信息</h2>
          <el-button plain size="mini" type="success" icon="fa fa-mail-forward" @click="returnList"> 返回</el-button>
        </div>

        <el-row>
          <el-form-item label="医院名称" prop="hospitalId">
            <el-select
              v-model="appointForm.hospitalId"
              filterable
              clearable
              reserve-keyword
              :loading="loadingIns"
              :disabled="disabledHospital"
              placeholder="请选择医院"
              @change="hospitalChange"
            >
              <el-option
                v-for="item in pickHospitalList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="科室名称" prop="officeId">
            <el-select
              v-model="appointForm.officeId"
              filterable
              clearable
              reserve-keyword
              :loading="loadingIns"
              :disabled="disabledOffice"
              placeholder="请选择科室"
              @change="officeChange"
            >
              <el-option
                v-for="item in pickOfficeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="医生名称" prop="doctorId">
            <el-select
              v-model="appointForm.doctorId"
              filterable
              clearable
              reserve-keyword
              :loading="loadingIns"
              :disabled="disabledDoctor"
              placeholder="请选择医生"
            >
              <el-option
                v-for="item in pickDoctorList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>

        <div class="tit">
          <h2>项目信息</h2>
          <el-button v-if="userRole !== 1" plain size="mini" type="success" icon="fa fa-mail-forward" @click="returnList"> 返回</el-button>
        </div>
        <el-row>
          <el-form-item label="项目分类" prop="classifyIdList">
            <el-cascader clearable :options="pickClassifyList"
                         :props="{ expandTrigger: 'hover' }"
                         class="filter-item"  style="width: 200px" v-model="classifyIdList"
                         placeholder="请选择分类" filterable @change="classifyChange">
            </el-cascader>
          </el-form-item>

          <el-form-item label="医检机构" prop="institutionId">
            <el-select
              v-model="appointForm.institutionId"
              filterable
              clearable
              reserve-keyword
              :loading="loadingIns"
              placeholder="请选择医检机构"
              @change="institutionChange"
            >
              <el-option
                v-for="item in pickInstitutionList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="科室名称" prop="insOfficeId">
            <el-select
              v-model="appointForm.insOfficeId"
              filterable
              clearable
              reserve-keyword
              placeholder="请选择科室"
              @change="insOfficeChange"
            >
              <el-option
                v-for="item in pickInsOfficeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-table :data="appointItemList" style="width: 100%;margin-top:10px" ref="multipleTable" @selection-change="changeSelect">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column width="250px" label="预约日期">
              <template slot-scope="scope">
              <el-date-picker v-model="scope.row.appointDate" type="datetime"
                              :default-value="timeDefaultShow"
                              value-format="yyyy-MM-dd HH:mm:ss"  placeholder="请选择预约日期"></el-date-picker>
              </template>
            </el-table-column>
            <el-table-column width="250px" label="时间">
              <!-- <el-form-item prop="appoinTime" >
                <el-input v-model="appointForm.appointTime" placeholder="08:00-09:00"></el-input>
              </el-form-item> -->
              <template slot-scope="scope">
                <el-input v-model="scope.row.appointTime" placeholder="08:00"></el-input>
              </template>
            </el-table-column>

            <el-table-column width="250px" label="项目名称">
              <template slot-scope="scope">
                <span>{{scope.row.itemName}}</span>
              </template>
            </el-table-column>
            <el-table-column min-width="80px" label="项目价格">
              <template slot-scope="scope">
                <span>{{scope.row.itemPrice}}</span>
              </template>
            </el-table-column>
            <el-table-column min-width="80px" label="检测时长">
              <template slot-scope="scope">
                <span>{{scope.row.itemTime}}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-row>

        <div class="tit">
          <h2>患者信息</h2>
        </div>
        <el-row>
          <el-form-item label="患者姓名" prop="patientName">
            <el-input  @keydown.native="keydown($event)" v-model.trim="appointForm.patientName" clearable></el-input>
          </el-form-item>
          <el-form-item label="患者身份证" prop="patientCard">
            <el-input @change="changeCard" v-model.trim="appointForm.patientCard" clearable></el-input>
          </el-form-item>
          <el-form-item label="患者性别" prop="patientSex">
            <el-radio-group v-model="appointForm.patientSex">
              <el-radio :label="item.value" :key="item.value" v-for="item in sexLabels">{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="患者年龄" prop="patientAge">
            <el-input v-model.trim="appointForm.patientAge" type="number"></el-input>
          </el-form-item>
          <el-form-item label="患者电话" prop="patientPhone">
            <el-input v-model.trim="appointForm.patientPhone" @change="changePhone" type="number" clearable></el-input>
          </el-form-item>
          <el-form-item label="患者病史" prop="patientInfo">
            <el-input type="textarea" v-model="appointForm.patientInfo"></el-input>
          </el-form-item>
          <el-form-item label="初步诊断" prop="examineMsg">
            <el-input type="textarea" v-model="appointForm.examineMsg"></el-input>
          </el-form-item>
          <el-form-item label="预约备注" prop="remark">
            <el-input type="textarea" v-model="appointForm.remark"></el-input>
          </el-form-item>
        </el-row>

        <div class="tit">
          <h2>上传病情</h2>
        </div>
        <el-row>
          <el-form-item prop="healthFiles">
            <upload-oss folder="appoint" accept="image,pdf" :limit="5" @uploadFileList="getHealthFiles" @chooseFileLength="getChooseFileLength"></upload-oss>
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item>
            <el-button type="primary" :disabled="disabledBtn" plain @click="sureAppointClick">保 存</el-button>
            <el-button @click="resetForm">取 消</el-button>
            <!-- <el-button @click="returnList">取 消</el-button> -->
          </el-form-item>
        </el-row>
      </el-form>
    </div>

  </div>
</template>

<script>
import * as message from '@/constants/message';
import Map from '@/components/Map';
import UploadOss from '@/components/UploadOss';
import { mapGetters, mapActions } from 'vuex';
import UserApi from "@/api/user/user";
import AppointApi from "@/api/appoint/appoint";
import OfficeApi from "@/api/institution/office";
import DoctorApi from "@/api/institution/doctor";
import AppointItemApi from "@/api/appoint/appointItem";
import HospitalApi from '@/api/institution/hospital';
import {getStorage} from "@/utils/auth";
import * as stn from "@/constants/storeName";
export default {
  data () {
    return {
      sexLabels: [
        { label: "男", value: 1 },
        { label: "女", value: 2 }
      ],
      projectIdsLimit: 10,
      chooseFileLength: 0,
      loadingIns: false,
      loadingCla: false,
      loadingUpload: false,
      fullscreenLoading: false,
      isCenter: true,
      disabled: false,
      uploadHeaders: {
        authorization: ''
      },
      disabledBtn: false,
      disabledHospital: false,
      disabledOffice: false,
      disabledDoctor: false,
      userRole: '',
      dialogImageUrl: '',
      dialogImageAlt: '',
      dialogVisible: false,
      dialogOfficeFormVisible: false,
      dialogDoctorFormVisible: false,
      withCredentials: true,
      addOfficeForm: {
        hospitalId: '',
        officeName: ''
      },
      addDoctorForm: {
        hospitalId: '',
        officeId: '',
        doctorName: '',
        doctorTitle: ''
      },
      pickHospitalList: [],
      pickOfficeList: [],
      pickDoctorList: [],
      appointForm: {
        hospitalId: '',
        officeId: '',
        doctorId: '',
        patientName: '',
        patientSex: '',
        patientAge: '',
        patientPhone: '',
        patientCard: '',
        patientInfo: '',
        examineMsg: '',
        itemId: '',
        itemList: [],
        institutionId: '',
        insOfficeId: '',
        appointDate: '',
        remark: '',
        appointTime: '',
        appointHealthFiles: []
      },
      /*pickerBeginDateBefore:{
        disabledDate(time) {
          return time.getTime() < Date.now();
        }
      },*/
      pickClassifyList: [],
      classifyIdList: [],
      pickInstitutionList: [],
      pickInsOfficeList: [],
      appointItemList: [],
      selectItemList: [],
      timeDefaultShow:'',
      roleRules: {
        /*appointDate: [
          {
            required: true,
            message: '请输入预约时间段',
            trigger: 'blur'
          }
        ],
        appointTime: [
          {
            required: true,
            message: '请选择预约日期',
            trigger: 'change'
          }
        ],
        classifyIdList: [
          {
            required: true,
            message: '请选择项目分类',
            trigger: 'change'
          }
        ],*/
        patientName: [
          {
            required: true,
            message: '请输入患者姓名',
            trigger: 'blur'
          }
        ],
         patientAge:[
          {
            pattern:/^([1-9]|[1-9]\d|1\d{2}|200)$/,
            message:"年龄输入错误",
            trigger:"blur"
          }
        ],
        patientPhone: [
          {
            required: true,
            message: '请输入患者电话',
            trigger: 'blur'
          }
        ],
        institutionId: [
          {
            required: true,
            message: '请选择医检机构',
            trigger: 'change'
          }
        ]
      }
    }
  },
  components: {
    Map,UploadOss
  },
  beforeRouteLeave(to,from,next){
    to.meta.keepAlive = true
    next()
  },
  methods: {
    ...mapGetters({
      openTabs: 'getOpenTabs'
    }),
    ...mapActions({
      setOpenTabs: 'setOpenTabs',
      setActiveIndexPath: 'setActiveIndexPath',
      setDeleteTabs: 'setDeleteTabs',
      replaceOpenTab: 'replaceOpenTab'
    }),
    init () {
      this.$Utils.clearData(this.appointForm)
      this.userInfo = getStorage(stn.USER_INFO);
      if (this.userInfo){
        this.userRole = this.userInfo.userRole;
      }
      this.listItemClassifyTree()
      this.listHospital()

      if (this.userRole != 1){
        this.getUserRelation();
      }
    },
    keydown(e) {
      if (e.keyCode == 32) {
        e.returnValue = false;
      }
    },
    changeCard(val){
      if(this.$Utils.isNull(val)){
        this.disabledBtn = false;
      }else{
        if(this.$Utils.isCardNo(val)){
          this.disabledBtn = false;
        }else{
          this.disabledBtn = true;
          this.$Utils.messageError("身份证格式错误");
        }
      }
    },
    changePhone(val){
      if(this.$Utils.isNull(val)){
        this.disabledBtn = false;
      }else{
        if(this.$Utils.isMobile(val)){
          this.disabledBtn = false;
        }else{
          this.disabledBtn = true;
          this.$Utils.messageError("电话号码格式错误");
        }
      }
    },
    // 上传病情文件组件传来的文件url集合
    getHealthFiles(val){
      if (val){
        this.$Utils.notifySuccess("上传成功");
      }
      this.appointForm.appointHealthFiles = val
    },
    getChooseFileLength(val){
      this.chooseFileLength = val
    },
    sureAppointClick () {
      let _this = this
      _this.$refs.appointForm.validate(valid => {
        if (valid) {
          _this.$confirm(
            message.MSG_CONFIRM_SAVE_ALTER,
            message.TITLE_PROMPT,
            {}
          ).then(() => {
            // add
            if (_this.chooseFileLength != _this.appointForm.appointHealthFiles.length){
              _this.$Utils.notifyError("请先上传文件");
            }else{
              _this.addAppoint()
            }
          })
        }
      })
    },
    resetForm(){
      this.$refs.appointForm.resetFields()
    },
    changeSelect(val){
      this.selectItemList = [];
      for (let i = 0; i < val.length; i ++){
        //console.log(JSON.stringify(val[i]))
        if (!val[i].appointDate || !val[i].appointTime){
          this.$message({
            title: message.TITLE_ERROR,
            message: '请输入预约日期和时间'
          })
          this.$refs.multipleTable.clearSelection();
          break;
        }
      }
      this.selectItemList = val;
    },
    listItemClassifyTree(query){
      let _this = this
      let cond = {
        classifyName: (!query || typeof query !== 'string') ? '' : query
      }
      AppointItemApi.listItemClassifyTree(cond)
        .then(res => {
          setTimeout(() => {
            _this.pickClassifyList = res.data
          }, 200)
        })
        .catch(error => {
          _this.pickClassifyList = []
          console.error(error)
        })
    },
    getUserRelation () {
      let _this = this
      let cond = {}
      UserApi.getUserRelation(cond)
        .then(res => {
          if (res.data){
            if (res.data.hospitalId){
              _this.appointForm.hospitalId = Number(res.data.hospitalId)
              _this.disabledHospital = true
            }
            _this.listOffice()
            if (res.data.officeId){
              _this.appointForm.officeId = Number(res.data.officeId)
              _this.disabledOffice = true

              _this.listDoctor()
              if (res.data.doctorId){
                _this.appointForm.doctorId = Number(res.data.doctorId)
                _this.disabledDoctor = true
              }
            }
          }
        })
    },

    listHospital () {
      let _this = this
      _this.loadingIns = true
      let cond = {
        hospitalType: 1
      }
      HospitalApi.getHospitalNameList(cond)
        .then(res => {
          setTimeout(() => {
            _this.loadingIns = false
            _this.pickHospitalList = res.data.map(item => {
              return {
                value: item.hospitalId,
                label: item.hospitalName
              }
            })
          }, 200)
        })
        .catch(error => {
          _this.pickHospitalList = []
          console.error(error)
        })
    },
    listOffice () {
      let _this = this
      let cond = {
        hospitalId: _this.appointForm.hospitalId
      }
      OfficeApi.getOfficeNames(cond)
        .then(res => {
          setTimeout(() => {
            _this.pickOfficeList = res.data.map(item => {
              return {
                value: item.officeId,
                label: item.officeName
              }
            })
          }, 200)
        })
    },
    listDoctor () {
      let _this = this
      let cond = {
        hospitalId: _this.appointForm.hospitalId,
        officeId: _this.appointForm.officeId
      }
      DoctorApi.getDoctorNames(cond)
        .then(res => {
          setTimeout(() => {
            _this.pickDoctorList = res.data.map(item => {
              return {
                value: item.doctorId,
                label: item.doctorName
              }
            })
          }, 200)
        })
    },

    hospitalChange () {
      let _this = this
      if (!_this.appointForm.hospitalId){
        this.$notify.error({
          title: message.TITLE_PROMPT,
          message: "请先选择医院"
        })
        return;
      }
      _this.pickOfficeList = [];
      _this.appointForm.officeId = "";
      _this.pickDoctorList = [];
      _this.appointForm.doctorId = "";
      _this.pickInstitutionList = []
      _this.appointForm.institutionId = "";
      let cond = {
        hospitalId: _this.appointForm.hospitalId
      }
      OfficeApi.getOfficeNames(cond)
        .then(res => {
          setTimeout(() => {
            _this.pickOfficeList = res.data.map(item => {
              return {
                value: item.officeId,
                label: item.officeName
              }
            })
          }, 200)
        })
    },
    officeChange () {
      let _this = this
      if (!_this.appointForm.hospitalId){
        this.$notify.error({
          title: message.TITLE_PROMPT,
          message: "请先选择医院"
        })
        return;
      }
      if (!_this.appointForm.officeId){
        this.$notify.error({
          title: message.TITLE_PROMPT,
          message: "请先选择科室"
        })
        return;
      }
      _this.pickDoctorList = [];
      _this.appointForm.doctorId = "";
      let cond = {
        hospitalId: _this.appointForm.hospitalId,
        officeId: _this.appointForm.officeId
      }
      DoctorApi.getDoctorNames(cond)
        .then(res => {
          setTimeout(() => {
            _this.pickDoctorList = res.data.map(item => {
              return {
                value: item.doctorId,
                label: item.doctorName
              }
            })
          }, 200)
        })
    },
    listInstitution () {
      let _this = this
      _this.loadingIns = true
      let cond = {
        classifyId: _this.classifyIdList[1],
        hospitalId: _this.appointForm.hospitalId
      }
      AppointApi.appointInsSelect(cond)
        .then(res => {
          setTimeout(() => {
            _this.loadingIns = false
            _this.pickInstitutionList = res.data.map(item => {
              return {
                value: item.institutionId,
                label: item.institutionName
              }
            })
          }, 200)
        })
        .catch(error => {
          _this.pickInstitutionList = []
          console.error(error)
        })
    },
    classifyChange(){
      this.listInstitution()
      this.appointItemList = []
      this.appointForm.institutionId = ''
    },
    institutionChange(){
      let _this = this
      _this.appointItemList = []
      let cond = {
        institutionId: _this.appointForm.institutionId
      }

      OfficeApi.getOfficeNames(cond)
        .then(res => {
          setTimeout(() => {
            _this.pickInsOfficeList = res.data.map(item => {
              return {
                value: item.officeId,
                label: item.officeName
              }
            })
          }, 200)
        })

      if (_this.classifyIdList.length > 0){
        cond.classifyId = _this.classifyIdList[1]
      }

      AppointApi.appointItemSelect(cond)
        .then(res => {
          _this.appointItemList = res.data;
        })
        .catch(error => {
          _this.appointItemList = []
          console.error(error)
        })
    },
    insOfficeChange(){
      let _this = this
      let cond = {
        institutionId: _this.appointForm.institutionId,
        insOfficeId: _this.appointForm.insOfficeId
      }
      if (_this.classifyIdList.length > 0){
        cond.classifyId = _this.classifyIdList[1]
      }

      AppointApi.appointItemSelect(cond)
        .then(res => {
          _this.appointItemList = res.data;
        })
        .catch(error => {
          _this.appointItemList = []
          console.error(error)
        })
    },
    addAppoint () {
      let regTime = /^(([0-2][0-3])|([0-1][0-9])):[0-5][0-9]$/
      let _this = this
      if (!_this.selectItemList || _this.selectItemList.length === 0){
        _this.$message({
          title: message.TITLE_ERROR,
          message: '请勾选预约项目'
        })
      }
      for(var i=0;i<_this.selectItemList.length;i++){
        if(!regTime.test(_this.selectItemList[i].appointTime)){
          _this.$notify.error({
            title: message.TITLE_ERROR,
            message: "时间输入错误"
          })
          return
        }
      }
      let appointFormData = {
        itemList: _this.selectItemList,
        patientName: _this.appointForm.patientName,
        patientSex: _this.appointForm.patientSex,
        patientAge: _this.appointForm.patientAge,
        patientCard: _this.appointForm.patientCard,
        patientPhone: _this.appointForm.patientPhone,
        patientInfo: _this.appointForm.patientInfo,
        examineMsg: _this.appointForm.examineMsg,
        remark: _this.appointForm.remark,
        appointHealthFiles: _this.appointForm.appointHealthFiles,
        institutionId: _this.appointForm.institutionId,
        insOfficeId: _this.appointForm.insOfficeId,
        hospitalId: _this.appointForm.hospitalId,
        officeId: _this.appointForm.officeId,
        doctorId: _this.appointForm.doctorId
      }
      AppointApi.addAppoint(appointFormData)
        .then(data => {
          this.$Utils.notifySuccess()
          this.returnList()
        })
    },
    returnList () {
      this.$store.dispatch('delView', this.$route);
      this.$router.push({ path: '/appoint/appointManagement' })
    }
  },
  mounted () {
    this.timeDefaultShow = new Date()
    this.appointForm.patientSex = 1
    this.init()
  }
}
</script>
<style lang="scss" src="@/assets/css/views/add.scss" scope>
</style>
<style scoped>
.main_box{
  position: absolute;
  width: calc(100% - 50px);
  height: calc(100vh - 113px);
  overflow: auto;
  border: 1px solid #e6e6e6;
  margin: 10px;
}
.add_wrap{
  border: none;
}
</style>
